#include <gtest/gtest.h>
#include <iostream>
#include <cstdlib>
#include <filesystem>

// 全局测试环境设置
class BuildSystemTestEnvironment : public ::testing::Environment {
public:
    void SetUp() override {
        std::cout << "Setting up build system test environment..." << std::endl;
        
        // 切换到项目根目录 (builder_gitee目录)
        std::filesystem::path project_path = std::filesystem::path(__FILE__).parent_path().parent_path();
        std::filesystem::current_path(project_path);
        
        // 设置BUILD_PROJECT_ROOT环境变量
        std::string project_root = project_path.string();
        setenv("BUILD_PROJECT_ROOT", project_root.c_str(), 1);
        std::cout << "Set BUILD_PROJECT_ROOT to: " << project_root << std::endl;
        
        // 清理之前的构建输出
        system("./build.sh -c > /dev/null 2>&1 || true");
        
        // 清理测试输出文件
        system("rm -f test_*.txt > /dev/null 2>&1 || true");
        
        std::cout << "Test environment setup completed." << std::endl;
    }
    
    void TearDown() override {
        std::cout << "Cleaning up build system test environment..." << std::endl;
        
        // 清理构建输出
        system("./build.sh -c > /dev/null 2>&1 || true");
        
        // 清理测试输出文件
        system("rm -f test_*.txt > /dev/null 2>&1 || true");
        
        std::cout << "Test environment cleanup completed." << std::endl;
    }
};

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    
    // 添加全局测试环境
    ::testing::AddGlobalTestEnvironment(new BuildSystemTestEnvironment);
    
    // 设置测试输出格式
    ::testing::FLAGS_gtest_color = "yes";
    ::testing::FLAGS_gtest_print_time = true;
    
    std::cout << "Starting Build System Tests..." << std::endl;
    std::cout << "==============================" << std::endl;
    
    return RUN_ALL_TESTS();
}